package com.daxt.controller.system;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.util.HttpWsUtil;
import com.daxt.common.util.SdkUtil;
import com.daxt.mapper.sys.*;
import com.daxt.model.dic.DicDocFrom;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.dto.FourADeptDto;
import com.daxt.model.dto.FourAUserDto;
import com.daxt.model.service.accept.vo.DicDocFroms;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.BaseUser;
import com.daxt.model.service.base.vo.UserDept;
import com.daxt.model.service.base.vo.UserRole;
import com.daxt.service.DeptService;
import com.daxt.utils.BaseUtil;
import com.mchange.lang.LongUtils;
import com.sxlq.dmapi.model.Org;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.model.service.base.vo.Dept;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "部门")
@RestController
public class DeptController {


    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @ApiOperation(value = "查询单个部门", notes = "")
    @GetMapping("/deptone")
    public Result<List<Dept>> findOne(@ApiParam(" 部门ID") @RequestParam(value = "deptId") String deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("id", deptId);
        List<Dept> list = deptMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }

    @ApiOperation(value = "同步外部部门信息,新", notes = "")
    @GetMapping("/dept/newsync")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> syncDeptInfoNew(){

        deptService.syncDeptInfoNew(null);

        return ResultUtil.success();
    }


    @ApiOperation(value = "查询上级部门", notes = "")
    @GetMapping("/dept/parent")
    public Result<List<Dept>> findParent(@ApiParam(" 部门ID") @RequestParam(value = "deptId") String deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("id", deptId);
        Dept dept = deptMapper.selectOne(queryWrapper);

        if(dept.getParentId()==0){
            List<Dept> list=new ArrayList();
            list.add(dept);
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
        }

        QueryWrapper<Dept> queryWrapper2 = new QueryWrapper<Dept>();
        queryWrapper2.eq("id",dept.getParentId());
        dept = deptMapper.selectOne(queryWrapper2);

        QueryWrapper<Dept> queryWrapper3 = new QueryWrapper<Dept>();
        queryWrapper3.eq("parentId",dept.getParentId());
        List<Dept> list =deptMapper.selectList(queryWrapper3);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
    }




    @ApiOperation(value = "查询全部部门", notes = "")
    @GetMapping("/dept")
    public Result<List<Dept>> findAll(@ApiParam("全宗ID") @RequestParam(value = "fondsId", required = false) String fondsId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        if (!StringUtils.isEmpty(fondsId)) queryWrapper.eq("fondsId", fondsId);
        queryWrapper.orderByAsc("sort");
        List<Dept> list = deptMapper.selectList(queryWrapper);
        List<Dept> data = new ArrayList<Dept>();

        getData(list, data);
        List<Dept> collect = data.stream().sorted(Comparator.comparing(Dept::getSort)).collect(Collectors.toList());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, collect);
    }

    private List<Dept> getData(List<Dept> list, List<Dept> data) {
        if (data.size() == 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getParentId().intValue() == 0) {
                    data.add(list.get(i));
                    //list.remove(list.get(i));
                }
            }
        }
        for (int i = 0; i < data.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (data.get(i).getId().intValue() == list.get(j).getParentId()) {
                    Dept dept = list.get(j);
                    if (!data.get(i).getChildren().contains(dept)) {
                        data.get(i).getChildren().add(dept);
                        getData(list, data.get(i).getChildren());
                    }
                }
            }
        }

        return data;
    }


    @ApiOperation(value = "添加", notes = "")
    @PostMapping("/dept")
    public Result<String> save(@RequestBody Dept entity) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("DeptName", entity.getDeptName());
        queryWrapper.eq("parentId",entity.getParentId());
        List<Dept> selectList = deptMapper.selectList(queryWrapper);
        if (selectList != null && selectList.size() > 0) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门已存在！！！", null);
        }

//		QueryWrapper<Dept> qw=new QueryWrapper<Dept>();
//		qw.select("max(id) as id");
//		Dept maxId = deptMapper.selectOne(qw);
        int rows = deptMapper.insert(entity);

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "修改", notes = "")
    @PutMapping("/dept")
    public Result<String> edit(@RequestBody Dept entity) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("DeptName", entity.getDeptName());
        queryWrapper.eq("parentId",entity.getParentId());
        queryWrapper.last("and id != " + entity.getId());
        List<Dept> selectList = deptMapper.selectList(queryWrapper);
        if (selectList != null && selectList.size() > 0) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门已存在！！！", null);
        }

        int rows = deptMapper.updateById(entity);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "删除", notes = "")
    @DeleteMapping("/dept/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> del(@PathVariable("id") String id) {

        //判断人员部门表中有无对应数据
        QueryWrapper<UserDept> userDeptQueryWrapper=new QueryWrapper<>();
        userDeptQueryWrapper.eq("deptId",id);
        int k=userDeptMapper.selectCount(userDeptQueryWrapper);

        //判断该部门下还有无人员
        QueryWrapper<BaseUser> queryWrapperUser=new QueryWrapper<>();
        queryWrapperUser.eq("deptIds",id);
        int j=userMapper.selectCount(queryWrapperUser);

        //判断该部门是否存在子目录
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("parentId", id);

        Dept selectById = deptMapper.selectById(id);
        if (selectById == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "数据不存在", null);
        }

        int i = deptMapper.selectCount(queryWrapper);
        if (i > 0 || j > 0 || k>0) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请先删除子数据", null);
        }

        int deleteById = deptMapper.deleteById(id);
        if (deleteById > 0) {
            return ResultUtil.data(deleteById > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
        }
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作失败", null);
    }


    @ApiOperation(value = "同步外部部门信息", notes = "")
    @GetMapping("/dept/sync")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> syncDeptInfo() {

        List<FourADeptDto> fourAUserDtoList = new ArrayList<>();

        deptMapper.delete(new QueryWrapper<Dept>().isNotNull("extId"));


        for (int i = 1; i < 100; i++) {
            List<FourADeptDto> tempList = HttpWsUtil.syscDeptData(i + "", "500");
//            List<FourADeptDto> tempList = HttpWsUtil.syscDeptData(i + "", "1000");
            if (BaseUtil.listIsNotNullElement(tempList)) {
                fourAUserDtoList.addAll(tempList);
            } else {
                break;
            }
            System.out.println("======同步外部部门信息====执行批次完：" + i);
        }


        for (FourADeptDto dto : fourAUserDtoList) {
            if (dto.getDeptStatus().equals("2")) continue;
            if (dto.getPid().trim().equals("0")) {
                Dept tempDept = deptService.getById(90000l);
                if (tempDept == null) {
                    //新建集团总部  二级目录
                    tempDept = new Dept();
                    tempDept.setId(90000l);
                    tempDept.setParentId(Long.parseLong(dto.getId()));
                    tempDept.setDeptName("集团总部");
                    tempDept.setSort(Integer.parseInt(dto.getNum()));
                    tempDept.setPDeptCode(dto.getDeptCode());
                    tempDept.setDeptCode("LQZDY00001");
                    tempDept.setPids(dto.getPids() + "LQZDY00001/");

                    deptService.saveOrUpdate(tempDept);
                }

            }


            QueryWrapper<Dept> qw = new QueryWrapper<Dept>();
            qw.eq("extId", dto.getId());
            Dept bean = deptMapper.selectOne(qw);
            if (null == bean) {
                bean = new Dept();
                bean.setId(Long.parseLong(dto.getId()));
                bean.setParentId(Long.parseLong(dto.getPid()));

                bean.setExtId(dto.getId());
                bean.setDeptName(dto.getName());
                bean.setId(Long.parseLong(dto.getId()));
                bean.setParentId(Long.parseLong(dto.getPid()));
                bean.setSort(Integer.parseInt(dto.getNum()));
                bean.setPids(dto.getPids());
                bean.setDeptCode(dto.getDeptCode());
                bean.setPDeptCode(dto.getPDeptCode());
                bean.setFondsId(dto.getFondsId());
                bean.setDeptRank(dto.getDeptRank());

            }
            bean.setDeptName(dto.getName());

            deptService.saveOrUpdate(bean);


        }

        QueryWrapper<Dept> qw = new QueryWrapper();
        qw.notIn("id","90000");
        qw.eq("deptRank","2");
        qw.notLike("deptName","公司");
        List<Dept> deptList = deptMapper.selectList(qw);
        //2级非公司部门
        deptList.forEach((Dept dept)->{
            String[] sArr = dept.getPids().split("/");
            String pidsStr = sArr[0] + "/LQZDY00001" + "/" + sArr[1];



            //子集
            QueryWrapper<Dept> qwDept = new QueryWrapper<Dept>();
            qwDept.like("pids",dept.getPids());
            List<Dept> deptSubset = deptMapper.selectList(qwDept);
            deptSubset.forEach((Dept d)->{
                d.setPids(pidsStr + "/"+ d.getDeptCode() + "/");
                deptMapper.updateById(d);

            });

            dept.setParentId(90000l);
            dept.setPids(pidsStr);
            deptMapper.updateById(dept);


        });




        return ResultUtil.success();

    }
//


    @ApiOperation(value = "设置全宗", notes = "")
    @PutMapping("/dept/{fondsId}/{deptId}")
    public Result<String> setFonds(@PathVariable("fondsId") String fondsId, @PathVariable("deptId") String deptId) {

        Dept dept = deptMapper.selectById(deptId);

        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.like("pids", dept.getPids());
        Dept updateDept = new Dept();
        updateDept.setFondsId(Long.parseLong(fondsId));

        int rows = deptMapper.update(updateDept, queryWrapper);

        return ResultUtil.result(rows);


    }


    @ApiOperation(value = "添加部门", notes = "")
    @PostMapping("/dept/organization")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveOrganization(@ApiParam("部门名称") @RequestParam("deptName") String deptName,@ApiParam("全宗id") @RequestParam("fondsId") Long fondsId,@ApiParam("上级部门Id") Long parentId) {



        if (isDeptNameExist(deptName,parentId,0L)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "组织已存在！！！", null);
        }

        if(!StringUtils.isEmpty(fondsId) && isWeiYiFonds(fondsId.toString(),parentId)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "违反全宗唯一原则！！！", null);
        }

        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<Dept>();
        deptQueryWrapper.select("max(id) id");

        long id=1L;
        Dept deptAutoId= deptMapper.selectOne(deptQueryWrapper);
        if(deptAutoId!=null){
            id= deptAutoId.getId();
            id+=2;
        }

        Dept dept=new Dept();
        dept.setDeptName(deptName);
        //根据上级id判断有多少条数据，若没有数据则sort为1，若存在数据则结果值加1
        QueryWrapper<Dept> queryWrapper2 = new QueryWrapper<Dept>();
        queryWrapper2.eq("parentId",parentId);
        int count= deptMapper.selectCount(queryWrapper2);
        if(count==0){
            dept.setSort(1);
        }else{
            dept.setSort(count+1);
        }

        if(parentId!=null){
            dept.setParentId(parentId);
        }else{
            dept.setParentId(0L);
        }
        dept.setFondsId(fondsId);

        //设置id值
        dept.setId(id);
        int rows = deptMapper.insert(dept);

        //设置pids、deptCode、pDeptCode字段的值
        if(dept.getParentId()==0){
            Dept dept1 =deptMapper.selectById(dept);
            dept1.setPids(dept1.getId()+"/");
            dept1.setDeptCode(dept1.getId().toString());
            dept1.setPDeptCode(0+"");
            deptMapper.updateById(dept1);
        }else{
            Dept deptPar=deptMapper.selectById(parentId);
            Dept dept1 =deptMapper.selectById(dept);
            dept1.setPids(deptPar.getPids()+dept1.getId()+"/");
            dept1.setDeptCode(dept1.getId().toString());
            dept1.setPDeptCode(parentId.toString());
            deptMapper.updateById(dept1);
        }

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    private boolean isDeptNameExist(String deptName,Long parentId,Long id){
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
        queryWrapper.eq("DeptName",deptName);
        queryWrapper.eq(parentId!=null , "parentId",parentId);
        queryWrapper.ne(id!=0&&id!=null,"id",id);
        List<Dept> selectList = deptMapper.selectList(queryWrapper);
        if (selectList != null && selectList.size() > 0) {
            return true;
        }else{
            return false;
        }
    }

    private boolean isWeiYiFonds(String fondsId,Long parentId){

        if(parentId!=null && parentId>1){
            return false;
        }
        if(parentId!=null && !RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5) && parentId==1){
            return false;
        }

        boolean flage=false;
        QueryWrapper<Dept> deptQueryWrapper=new QueryWrapper<>();
        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            deptQueryWrapper.eq("parentId",1);
        }else{
            deptQueryWrapper.eq("parentId",0);
        }
        deptQueryWrapper.eq("fondsId",fondsId);
        int count= deptMapper.selectCount(deptQueryWrapper);
        if(count>0){
            flage=true;
        }


        return flage;
    }


    @ApiOperation(value = "修改部门", notes = "")
    @PostMapping("/dept/modify")
    public Result<String> modifyDept(@RequestBody Dept dept) {

        if (StringUtils.isEmpty(dept.getId())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "id不能为空！！！", null);
        }
        if (StringUtils.isEmpty(dept.getDeptName())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门名称不能为空！！！", null);
        }
        if (StringUtils.isEmpty(dept.getParentId())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上级部门不能为空！！！", null);
        }

        if (isDeptNameExist(dept.getDeptName(),dept.getParentId(),dept.getId())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "组织已存在！！！", null);
        }

        if(!StringUtils.isEmpty(dept.getFondsId()) && isWeiYiFonds(dept.getFondsId().toString(),dept.getParentId())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "违反全宗唯一原则！！！", null);
        }

        int rows = deptMapper.updateById(dept);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, null);
    }

    @ApiOperation(value = "查询系统来源架构", notes = "")
    @GetMapping("/dept/source")
    @LoginAuth()
    public Result<List<Dept>> getSourceDept(@ApiIgnore @LoginUser UserInfo loginUser) {
        List<Dept> deptList= deptService.getSourceDept(loginUser);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, deptList);
    }



}
